<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registry Engine 测试演示</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(45deg, #2c3e50, #34495e);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            margin: 0;
            font-size: 2.8em;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .header p {
            margin: 15px 0 0 0;
            opacity: 0.9;
            font-size: 1.2em;
        }

        .main-content {
            display: grid;
            grid-template-columns: 350px 1fr;
            min-height: 700px;
        }

        .sidebar {
            background: #f8f9fa;
            padding: 25px;
            border-right: 1px solid #e0e0e0;
        }

        .content {
            padding: 25px;
        }

        .demo-section {
            margin-bottom: 25px;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .demo-header {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            font-weight: bold;
            color: #2c3e50;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .demo-body {
            padding: 20px;
        }

        .demo-button {
            background: linear-gradient(45deg, #3498db, #2980b9);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            cursor: pointer;
            margin: 8px;
            transition: all 0.3s;
            font-size: 14px;
            min-width: 120px;
        }

        .demo-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(52, 152, 219, 0.4);
        }

        .demo-button:active {
            transform: translateY(0);
        }

        .demo-button.success {
            background: linear-gradient(45deg, #27ae60, #229954);
        }

        .demo-button.warning {
            background: linear-gradient(45deg, #f39c12, #e67e22);
        }

        .demo-button.danger {
            background: linear-gradient(45deg, #e74c3c, #c0392b);
        }

        .demo-button.info {
            background: linear-gradient(45deg, #8e44ad, #7d3c98);
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .stat-value {
            font-size: 2.2em;
            font-weight: bold;
            margin-bottom: 8px;
        }

        .stat-label {
            opacity: 0.9;
            font-size: 0.9em;
        }

        .log-container {
            background: #1e1e1e;
            color: #00ff00;
            padding: 20px;
            border-radius: 8px;
            height: 400px;
            overflow-y: auto;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 13px;
            margin-top: 20px;
            border: 2px solid #333;
        }

        .log-entry {
            margin-bottom: 8px;
            padding: 4px 0;
            border-bottom: 1px solid #333;
            animation: fadeIn 0.3s ease-in;
        }

        .log-time {
            color: #888;
            margin-right: 12px;
            font-size: 11px;
        }

        .log-level-info { color: #00ff00; }
        .log-level-warn { color: #ffff00; }
        .log-level-error { color: #ff4444; }
        .log-level-success { color: #00ffaa; }

        .input-group {
            margin: 15px 0;
        }

        .input-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #2c3e50;
        }

        .input-group input, .input-group select, .input-group textarea {
            width: 100%;
            padding: 10px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-family: inherit;
            transition: border-color 0.3s;
        }

        .input-group input:focus, .input-group select:focus, .input-group textarea:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 10px rgba(52, 152, 219, 0.2);
        }

        .input-group textarea {
            height: 100px;
            resize: vertical;
            font-family: 'Consolas', monospace;
        }

        .result-display {
            background: #f8f9fa;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
            max-height: 300px;
            overflow-y: auto;
        }

        .result-item {
            background: white;
            border: 1px solid #ddd;
            border-radius: 6px;
            padding: 12px;
            margin-bottom: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }

        .result-title {
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 8px;
        }

        .result-content {
            font-family: 'Consolas', monospace;
            font-size: 12px;
            color: #555;
            white-space: pre-wrap;
        }

        .clear-button {
            background: #6c757d;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
            float: right;
            margin-bottom: 10px;
        }

        .performance-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-left: 8px;
        }

        .performance-excellent { background: #27ae60; }
        .performance-good { background: #f39c12; }
        .performance-poor { background: #e74c3c; }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.6; }
            100% { opacity: 1; }
        }

        .pulsing {
            animation: pulse 1.5s infinite;
        }

        .accordion {
            margin-top: 20px;
        }

        .accordion-item {
            border: 1px solid #ddd;
            border-radius: 6px;
            margin-bottom: 10px;
            overflow: hidden;
        }

        .accordion-header {
            background: #f8f9fa;
            padding: 15px;
            cursor: pointer;
            font-weight: bold;
            user-select: none;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .accordion-header:hover {
            background: #e9ecef;
        }

        .accordion-content {
            display: none;
            padding: 15px;
            background: white;
        }

        .accordion-content.active {
            display: block;
        }

        .code-block {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 12px;
            font-family: 'Consolas', monospace;
            font-size: 12px;
            margin: 10px 0;
            overflow-x: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 Registry Engine 测试演示</h1>
            <p>ThingsPanel 物联网可视化平台 - 统一注册管理系统演示</p>
        </div>

        <div class="main-content">
            <div class="sidebar">
                <h3>📊 实时统计</h3>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-value" id="totalItems">0</div>
                        <div class="stat-label">总注册项</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="enabledItems">0</div>
                        <div class="stat-label">启用项目</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="itemTypes">0</div>
                        <div class="stat-label">项目类型</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="performance">-</div>
                        <div class="stat-label">性能指标</div>
                    </div>
                </div>

                <h3>🎛️ 控制面板</h3>
                <button class="demo-button success" onclick="initializeDemo()">初始化演示</button>
                <button class="demo-button info" onclick="runPerformanceTest()">性能测试</button>
                <button class="demo-button warning" onclick="runErrorTest()">错误测试</button>
                <button class="demo-button danger" onclick="clearAllData()">清空数据</button>
                <button class="clear-button" onclick="clearLogs()">清空日志</button>

                <h3>📋 类型分布</h3>
                <div id="typeDistribution"></div>

                <h3>🏷️ 分类统计</h3>
                <div id="categoryStats"></div>
            </div>

            <div class="content">
                <div class="demo-section">
                    <div class="demo-header">
                        <span>🎯 基础注册操作</span>
                    </div>
                    <div class="demo-body">
                        <p>演示Registry Engine的基本注册和查询功能</p>
                        <button class="demo-button" onclick="registerBasicComponent()">注册基础组件</button>
                        <button class="demo-button" onclick="registerWithDependencies()">注册依赖组件</button>
                        <button class="demo-button" onclick="queryComponents()">查询组件</button>
                        <button class="demo-button" onclick="testValidation()">验证测试</button>
                    </div>
                </div>

                <div class="demo-section">
                    <div class="demo-header">
                        <span>📦 批量操作演示</span>
                    </div>
                    <div class="demo-body">
                        <p>演示大量组件的批量注册和管理</p>
                        <div class="input-group">
                            <label for="batchCount">批量注册数量:</label>
                            <input type="number" id="batchCount" value="50" min="1" max="500">
                        </div>
                        <button class="demo-button" onclick="batchRegisterComponents()">批量注册</button>
                        <button class="demo-button" onclick="batchQueryComponents()">批量查询</button>
                        <button class="demo-button" onclick="complexQuery()">复杂查询</button>
                    </div>
                </div>

                <div class="demo-section">
                    <div class="demo-header">
                        <span>🔗 依赖关系管理</span>
                    </div>
                    <div class="demo-body">
                        <p>演示组件依赖关系的建立和验证</p>
                        <button class="demo-button" onclick="createDependencyChain()">创建依赖链</button>
                        <button class="demo-button" onclick="validateDependencies()">验证依赖</button>
                        <button class="demo-button" onclick="analyzeDependencies()">依赖分析</button>
                        <button class="demo-button" onclick="testCircularDependency()">循环依赖测试</button>
                    </div>
                </div>

                <div class="demo-section">
                    <div class="demo-header">
                        <span>🛠️ 自定义组件测试</span>
                    </div>
                    <div class="demo-body">
                        <div class="input-group">
                            <label for="customId">组件ID:</label>
                            <input type="text" id="customId" placeholder="例: my-weather-widget" value="my-weather-widget">
                        </div>
                        <div class="input-group">
                            <label for="customName">组件名称:</label>
                            <input type="text" id="customName" placeholder="例: 天气组件" value="天气组件">
                        </div>
                        <div class="input-group">
                            <label for="customType">组件类型:</label>
                            <select id="customType">
                                <option value="card21-component">Card2.1组件</option>
                                <option value="legacy-card-component">传统Card组件</option>
                                <option value="visual-editor-component">可视化编辑器组件</option>
                                <option value="renderer">渲染器</option>
                                <option value="data-source">数据源</option>
                                <option value="template">模板</option>
                            </select>
                        </div>
                        <div class="input-group">
                            <label for="customContent">组件内容 (JSON):</label>
                            <textarea id="customContent" placeholder='{"type": "weather-widget", "config": {}}'>{
  "type": "weather-widget",
  "dataSources": [
    {
      "key": "weather",
      "type": "api",
      "url": "/api/weather"
    }
  ],
  "staticParams": {
    "refreshInterval": 300000,
    "showForecast": true
  }
}</textarea>
                        </div>
                        <button class="demo-button" onclick="registerCustomComponent()">注册自定义组件</button>
                        <button class="demo-button" onclick="queryCustomComponent()">查询自定义组件</button>
                    </div>
                </div>

                <div class="demo-section">
                    <div class="demo-header">
                        <span>📈 结果展示</span>
                    </div>
                    <div class="demo-body">
                        <div class="result-display" id="resultDisplay"></div>
                    </div>
                </div>

                <div class="log-container" id="logContainer">
                    <div class="log-entry">
                        <span class="log-time">[系统]</span>
                        <span class="log-level-info">Registry Engine 演示系统已启动</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 模拟Registry Engine功能
        class DemoRegistryEngine {
            constructor() {
                this.items = new Map()
                this.typeIndex = new Map()
                this.categoryIndex = new Map()
                this.tagIndex = new Map()
                this.dependencyGraph = new Map()
                this.reverseDependencyGraph = new Map()
                this.performanceData = []
                this.eventListeners = new Map()
            }

            async register(item) {
                const startTime = performance.now()

                try {
                    // 验证必需字段
                    if (!item.metadata.id || !item.metadata.name || !item.metadata.type) {
                        throw new Error('缺少必需的元数据字段')
                    }

                    // 检查ID唯一性
                    if (this.items.has(item.metadata.id)) {
                        throw new Error(`项目 ${item.metadata.id} 已存在`)
                    }

                    // 执行验证
                    if (item.validate && !await item.validate()) {
                        throw new Error('项目验证失败')
                    }

                    // 存储项目
                    this.items.set(item.metadata.id, item)

                    // 更新索引
                    this.updateIndexes(item.metadata, 'add')

                    // 执行初始化
                    if (item.initialize) {
                        await item.initialize()
                    }

                    const duration = performance.now() - startTime
                    this.performanceData.push(duration)
                    if (this.performanceData.length > 100) {
                        this.performanceData.shift()
                    }

                    this.emit('register', item.metadata)

                    logMessage(`✅ 成功注册: ${item.metadata.type}/${item.metadata.id}`, 'success')
                    return true

                } catch (error) {
                    logMessage(`❌ 注册失败: ${error.message}`, 'error')
                    this.emit('error', { action: 'register', error, metadata: item.metadata })
                    return false
                }
            }

            async unregister(id) {
                try {
                    const item = this.items.get(id)
                    if (!item) {
                        logMessage(`⚠️ 项目 ${id} 不存在`, 'warn')
                        return false
                    }

                    // 执行清理
                    if (item.cleanup) {
                        await item.cleanup()
                    }

                    // 更新索引
                    this.updateIndexes(item.metadata, 'remove')

                    // 删除项目
                    this.items.delete(id)

                    this.emit('unregister', id)
                    logMessage(`🗑️ 成功注销: ${id}`, 'info')
                    return true

                } catch (error) {
                    logMessage(`❌ 注销失败: ${error.message}`, 'error')
                    return false
                }
            }

            get(id) {
                return this.items.get(id) || null
            }

            has(id) {
                return this.items.has(id)
            }

            query(conditions = {}) {
                let results = Array.from(this.items.values())

                if (conditions.type) {
                    const types = Array.isArray(conditions.type) ? conditions.type : [conditions.type]
                    results = results.filter(item => types.includes(item.metadata.type))
                }

                if (conditions.enabled !== undefined) {
                    results = results.filter(item => item.metadata.enabled === conditions.enabled)
                }

                if (conditions.category) {
                    results = results.filter(item => item.metadata.category === conditions.category)
                }

                if (conditions.tags) {
                    results = results.filter(item => {
                        if (!item.metadata.tags) return false
                        return conditions.tags.every(tag => item.metadata.tags.includes(tag))
                    })
                }

                if (conditions.filter) {
                    results = results.filter(conditions.filter)
                }

                return results
            }

            getByType(type) {
                const ids = this.typeIndex.get(type)
                if (!ids) return []
                return Array.from(ids).map(id => this.items.get(id)).filter(Boolean)
            }

            getByCategory(category) {
                const ids = this.categoryIndex.get(category)
                if (!ids) return []
                return Array.from(ids).map(id => this.items.get(id)).filter(Boolean)
            }

            getByTag(tag) {
                const ids = this.tagIndex.get(tag)
                if (!ids) return []
                return Array.from(ids).map(id => this.items.get(id)).filter(Boolean)
            }

            getDependencies(id, recursive = false) {
                const direct = this.dependencyGraph.get(id)
                if (!direct) return []

                if (!recursive) {
                    return Array.from(direct)
                }

                const allDeps = new Set()
                const visited = new Set()

                const collectDeps = (itemId) => {
                    if (visited.has(itemId)) return
                    visited.add(itemId)

                    const deps = this.dependencyGraph.get(itemId)
                    if (deps) {
                        for (const dep of deps) {
                            allDeps.add(dep)
                            collectDeps(dep)
                        }
                    }
                }

                collectDeps(id)
                return Array.from(allDeps)
            }

            getDependents(id, recursive = false) {
                const direct = this.reverseDependencyGraph.get(id)
                if (!direct) return []

                if (!recursive) {
                    return Array.from(direct)
                }

                const allDependents = new Set()
                const visited = new Set()

                const collectDependents = (itemId) => {
                    if (visited.has(itemId)) return
                    visited.add(itemId)

                    const dependents = this.reverseDependencyGraph.get(itemId)
                    if (dependents) {
                        for (const dependent of dependents) {
                            allDependents.add(dependent)
                            collectDependents(dependent)
                        }
                    }
                }

                collectDependents(id)
                return Array.from(allDependents)
            }

            getStats() {
                const items = Array.from(this.items.values())
                const byType = {}
                const byCategory = {}
                let enabled = 0
                let withDependencies = 0
                let lastUpdated = 0

                for (const item of items) {
                    const { metadata } = item

                    byType[metadata.type] = (byType[metadata.type] || 0) + 1

                    if (metadata.category) {
                        byCategory[metadata.category] = (byCategory[metadata.category] || 0) + 1
                    }

                    if (metadata.enabled) enabled++
                    if (metadata.dependencies && metadata.dependencies.length > 0) withDependencies++
                    if (metadata.updatedAt > lastUpdated) lastUpdated = metadata.updatedAt
                }

                return {
                    total: items.length,
                    byType,
                    byCategory,
                    enabled,
                    disabled: items.length - enabled,
                    withDependencies,
                    lastUpdated
                }
            }

            getAll() {
                return Array.from(this.items.values())
            }

            async clear() {
                const items = Array.from(this.items.values())
                for (const item of items) {
                    await this.unregister(item.metadata.id)
                }

                this.items.clear()
                this.typeIndex.clear()
                this.categoryIndex.clear()
                this.tagIndex.clear()
                this.dependencyGraph.clear()
                this.reverseDependencyGraph.clear()

                this.emit('clear')
                logMessage('🧹 已清空所有注册项', 'info')
            }

            getAveragePerformance() {
                if (this.performanceData.length === 0) return 0
                return this.performanceData.reduce((a, b) => a + b, 0) / this.performanceData.length
            }

            updateIndexes(metadata, action) {
                const { id, type, category, tags, dependencies } = metadata

                // 类型索引
                if (action === 'add') {
                    if (!this.typeIndex.has(type)) {
                        this.typeIndex.set(type, new Set())
                    }
                    this.typeIndex.get(type).add(id)
                } else {
                    const typeSet = this.typeIndex.get(type)
                    if (typeSet) {
                        typeSet.delete(id)
                        if (typeSet.size === 0) {
                            this.typeIndex.delete(type)
                        }
                    }
                }

                // 分类索引
                if (category) {
                    if (action === 'add') {
                        if (!this.categoryIndex.has(category)) {
                            this.categoryIndex.set(category, new Set())
                        }
                        this.categoryIndex.get(category).add(id)
                    } else {
                        const categorySet = this.categoryIndex.get(category)
                        if (categorySet) {
                            categorySet.delete(id)
                            if (categorySet.size === 0) {
                                this.categoryIndex.delete(category)
                            }
                        }
                    }
                }

                // 标签索引
                if (tags) {
                    for (const tag of tags) {
                        if (action === 'add') {
                            if (!this.tagIndex.has(tag)) {
                                this.tagIndex.set(tag, new Set())
                            }
                            this.tagIndex.get(tag).add(id)
                        } else {
                            const tagSet = this.tagIndex.get(tag)
                            if (tagSet) {
                                tagSet.delete(id)
                                if (tagSet.size === 0) {
                                    this.tagIndex.delete(tag)
                                }
                            }
                        }
                    }
                }

                // 依赖关系
                if (dependencies && dependencies.length > 0) {
                    if (action === 'add') {
                        this.dependencyGraph.set(id, new Set(dependencies))
                        for (const depId of dependencies) {
                            if (!this.reverseDependencyGraph.has(depId)) {
                                this.reverseDependencyGraph.set(depId, new Set())
                            }
                            this.reverseDependencyGraph.get(depId).add(id)
                        }
                    } else {
                        this.dependencyGraph.delete(id)
                        for (const depId of dependencies) {
                            const reverseSet = this.reverseDependencyGraph.get(depId)
                            if (reverseSet) {
                                reverseSet.delete(id)
                                if (reverseSet.size === 0) {
                                    this.reverseDependencyGraph.delete(depId)
                                }
                            }
                        }
                    }
                }
            }

            on(event, handler) {
                if (!this.eventListeners.has(event)) {
                    this.eventListeners.set(event, new Set())
                }
                this.eventListeners.get(event).add(handler)

                return () => {
                    const handlers = this.eventListeners.get(event)
                    if (handlers) {
                        handlers.delete(handler)
                        if (handlers.size === 0) {
                            this.eventListeners.delete(event)
                        }
                    }
                }
            }

            emit(event, data) {
                const handlers = this.eventListeners.get(event)
                if (handlers) {
                    for (const handler of handlers) {
                        try {
                            handler(data)
                        } catch (error) {
                            console.error('Event handler error:', error)
                        }
                    }
                }
            }
        }

        // 创建演示实例
        const registryEngine = new DemoRegistryEngine()

        // 日志系统
        function logMessage(message, level = 'info', data = null) {
            const logContainer = document.getElementById('logContainer')
            const logEntry = document.createElement('div')
            logEntry.className = 'log-entry'

            const now = new Date()
            const timeStr = now.toLocaleTimeString()

            let logHtml = `<span class="log-time">[${timeStr}]</span>`
            logHtml += `<span class="log-level-${level}">${message}</span>`

            if (data && typeof data === 'object') {
                logHtml += `<br><span style="color: #888; font-size: 11px; margin-left: 60px;">数据: ${JSON.stringify(data, null, 2)}</span>`
            }

            logEntry.innerHTML = logHtml
            logContainer.appendChild(logEntry)
            logContainer.scrollTop = logContainer.scrollHeight

            // 限制日志条数
            while (logContainer.children.length > 150) {
                logContainer.removeChild(logContainer.firstChild)
            }

            // 添加高亮效果
            logEntry.classList.add('pulsing')
            setTimeout(() => {
                logEntry.classList.remove('pulsing')
            }, 1500)
        }

        function clearLogs() {
            document.getElementById('logContainer').innerHTML = ''
            logMessage('日志已清空', 'info')
        }

        // 更新统计信息
        function updateStats() {
            const stats = registryEngine.getStats()
            const avgPerformance = registryEngine.getAveragePerformance()

            document.getElementById('totalItems').textContent = stats.total
            document.getElementById('enabledItems').textContent = stats.enabled
            document.getElementById('itemTypes').textContent = Object.keys(stats.byType).length

            const perfElement = document.getElementById('performance')
            if (avgPerformance > 0) {
                perfElement.textContent = avgPerformance.toFixed(2) + 'ms'

                // 性能指示器
                perfElement.className = 'stat-value'
                if (avgPerformance < 1) {
                    perfElement.innerHTML += '<span class="performance-indicator performance-excellent"></span>'
                } else if (avgPerformance < 5) {
                    perfElement.innerHTML += '<span class="performance-indicator performance-good"></span>'
                } else {
                    perfElement.innerHTML += '<span class="performance-indicator performance-poor"></span>'
                }
            }

            // 更新类型分布
            const typeDistribution = document.getElementById('typeDistribution')
            typeDistribution.innerHTML = ''
            for (const [type, count] of Object.entries(stats.byType)) {
                const item = document.createElement('div')
                item.style.cssText = 'padding: 5px; margin: 2px 0; background: #e9ecef; border-radius: 3px; font-size: 12px;'
                item.textContent = `${type}: ${count}`
                typeDistribution.appendChild(item)
            }

            // 更新分类统计
            const categoryStats = document.getElementById('categoryStats')
            categoryStats.innerHTML = ''
            for (const [category, count] of Object.entries(stats.byCategory)) {
                const item = document.createElement('div')
                item.style.cssText = 'padding: 5px; margin: 2px 0; background: #d1ecf1; border-radius: 3px; font-size: 12px;'
                item.textContent = `${category}: ${count}`
                categoryStats.appendChild(item)
            }
        }

        // 显示结果
        function displayResult(title, content) {
            const resultDisplay = document.getElementById('resultDisplay')

            const resultItem = document.createElement('div')
            resultItem.className = 'result-item'

            const titleElement = document.createElement('div')
            titleElement.className = 'result-title'
            titleElement.textContent = title

            const contentElement = document.createElement('div')
            contentElement.className = 'result-content'
            contentElement.textContent = typeof content === 'string' ? content : JSON.stringify(content, null, 2)

            resultItem.appendChild(titleElement)
            resultItem.appendChild(contentElement)
            resultDisplay.appendChild(resultItem)

            // 限制显示条数
            while (resultDisplay.children.length > 10) {
                resultDisplay.removeChild(resultDisplay.firstChild)
            }
        }

        // 演示函数
        async function initializeDemo() {
            logMessage('🚀 初始化演示数据...', 'info')

            // 注册一些基础组件
            const basicComponents = [
                {
                    metadata: {
                        id: 'temperature-sensor',
                        name: '温度传感器',
                        type: 'card21-component',
                        version: '1.0.0',
                        description: '用于显示温度数据的传感器组件',
                        category: 'sensors',
                        tags: ['sensor', 'temperature', 'iot'],
                        createdAt: Date.now(),
                        updatedAt: Date.now(),
                        enabled: true,
                        priority: 10
                    },
                    content: {
                        type: 'temperature-sensor',
                        dataSources: [{ key: 'temp', type: 'device' }]
                    }
                },
                {
                    metadata: {
                        id: 'humidity-sensor',
                        name: '湿度传感器',
                        type: 'card21-component',
                        version: '1.0.0',
                        category: 'sensors',
                        tags: ['sensor', 'humidity', 'iot'],
                        createdAt: Date.now(),
                        updatedAt: Date.now(),
                        enabled: true,
                        priority: 10
                    },
                    content: {
                        type: 'humidity-sensor',
                        dataSources: [{ key: 'humidity', type: 'device' }]
                    }
                },
                {
                    metadata: {
                        id: 'chart-renderer',
                        name: '图表渲染器',
                        type: 'renderer',
                        version: '2.0.0',
                        category: 'visualization',
                        tags: ['chart', 'renderer', 'visualization'],
                        createdAt: Date.now(),
                        updatedAt: Date.now(),
                        enabled: true,
                        priority: 20
                    },
                    content: {
                        type: 'chart-renderer',
                        supportedCharts: ['line', 'bar', 'pie']
                    }
                }
            ]

            for (const component of basicComponents) {
                await registryEngine.register(component)
            }

            updateStats()
            logMessage('✅ 演示数据初始化完成', 'success')
        }

        async function registerBasicComponent() {
            const component = {
                metadata: {
                    id: 'demo-component-' + Date.now(),
                    name: '演示组件',
                    type: 'card21-component',
                    version: '1.0.0',
                    description: '这是一个演示用的基础组件',
                    category: 'demo',
                    tags: ['demo', 'test'],
                    createdAt: Date.now(),
                    updatedAt: Date.now(),
                    enabled: true,
                    priority: 5
                },
                content: {
                    type: 'demo-component',
                    config: { demo: true }
                },
                validate: () => {
                    logMessage('🔍 执行组件验证...', 'info')
                    return true
                },
                initialize: async () => {
                    logMessage('🚀 执行组件初始化...', 'info')
                }
            }

            const success = await registryEngine.register(component)
            updateStats()

            if (success) {
                displayResult('基础组件注册', component.metadata)
            }
        }

        async function registerWithDependencies() {
            // 先注册依赖组件
            const dependency = {
                metadata: {
                    id: 'data-service',
                    name: '数据服务',
                    type: 'data-source',
                    version: '1.0.0',
                    category: 'service',
                    tags: ['service', 'data'],
                    createdAt: Date.now(),
                    updatedAt: Date.now(),
                    enabled: true,
                    priority: 100
                },
                content: { type: 'data-service' }
            }

            await registryEngine.register(dependency)

            // 注册有依赖的组件
            const dependentComponent = {
                metadata: {
                    id: 'chart-with-data',
                    name: '数据图表',
                    type: 'card21-component',
                    version: '1.0.0',
                    category: 'visualization',
                    tags: ['chart', 'data'],
                    dependencies: ['data-service'],
                    createdAt: Date.now(),
                    updatedAt: Date.now(),
                    enabled: true,
                    priority: 50
                },
                content: {
                    type: 'chart-with-data',
                    dataSources: [{ key: 'chartData', service: 'data-service' }]
                }
            }

            const success = await registryEngine.register(dependentComponent)
            updateStats()

            if (success) {
                displayResult('依赖组件注册', {
                    component: dependentComponent.metadata,
                    dependencies: registryEngine.getDependencies('chart-with-data')
                })
            }
        }

        function queryComponents() {
            const sensorComponents = registryEngine.query({
                type: 'card21-component',
                tags: ['sensor']
            })

            const allComponents = registryEngine.getAll()

            displayResult('组件查询结果', {
                传感器组件数量: sensorComponents.length,
                总组件数: allComponents.length,
                传感器组件: sensorComponents.map(c => c.metadata.name)
            })

            logMessage(`📊 查询完成: 找到 ${sensorComponents.length} 个传感器组件`, 'info')
        }

        async function testValidation() {
            // 测试验证失败的组件
            const invalidComponent = {
                metadata: {
                    id: 'invalid-component',
                    name: '',  // 空名称
                    type: 'card21-component',
                    version: '',
                    createdAt: Date.now(),
                    updatedAt: Date.now(),
                    enabled: true,
                    priority: 0
                },
                content: {},
                validate: () => {
                    logMessage('❌ 组件验证失败', 'error')
                    return false
                }
            }

            const result = await registryEngine.register(invalidComponent)
            updateStats()

            displayResult('验证测试结果', {
                注册结果: result ? '成功' : '失败（预期）',
                验证功能: '正常工作'
            })
        }

        async function batchRegisterComponents() {
            const count = parseInt(document.getElementById('batchCount').value) || 50
            logMessage(`📦 开始批量注册 ${count} 个组件...`, 'info')

            const startTime = performance.now()
            const promises = []

            for (let i = 0; i < count; i++) {
                const component = {
                    metadata: {
                        id: `batch-component-${i}`,
                        name: `批量组件 ${i}`,
                        type: 'card21-component',
                        version: '1.0.0',
                        category: i % 3 === 0 ? 'sensors' : i % 3 === 1 ? 'controls' : 'displays',
                        tags: ['batch', 'test', `group-${Math.floor(i / 10)}`],
                        createdAt: Date.now(),
                        updatedAt: Date.now(),
                        enabled: Math.random() > 0.1,
                        priority: Math.floor(Math.random() * 100)
                    },
                    content: {
                        type: `batch-component-${i}`,
                        index: i,
                        data: Math.random() * 100
                    }
                }

                promises.push(registryEngine.register(component))
            }

            const results = await Promise.all(promises)
            const duration = performance.now() - startTime
            const successCount = results.filter(r => r).length

            updateStats()

            displayResult('批量注册结果', {
                总数: count,
                成功: successCount,
                失败: count - successCount,
                耗时: `${duration.toFixed(2)}ms`,
                平均耗时: `${(duration / count).toFixed(2)}ms/个`
            })

            logMessage(`✅ 批量注册完成: ${successCount}/${count} 成功`, 'success')
        }

        function batchQueryComponents() {
            const startTime = performance.now()

            const sensorComponents = registryEngine.query({
                category: 'sensors',
                enabled: true
            })

            const batchComponents = registryEngine.query({
                tags: ['batch']
            })

            const duration = performance.now() - startTime

            displayResult('批量查询结果', {
                传感器组件: sensorComponents.length,
                批量组件: batchComponents.length,
                查询耗时: `${duration.toFixed(2)}ms`
            })

            logMessage(`🔍 批量查询完成，耗时 ${duration.toFixed(2)}ms`, 'info')
        }

        function complexQuery() {
            const startTime = performance.now()

            const complexResults = registryEngine.query({
                type: 'card21-component',
                enabled: true,
                filter: (item) => {
                    return item.metadata.priority > 20 &&
                           item.metadata.tags &&
                           item.metadata.tags.length >= 2 &&
                           item.metadata.name.includes('组件')
                }
            })

            const duration = performance.now() - startTime

            displayResult('复杂查询结果', {
                匹配条件: '类型=card21-component, 启用=true, 优先级>20, 标签>=2个, 名称包含"组件"',
                结果数量: complexResults.length,
                查询耗时: `${duration.toFixed(2)}ms`,
                匹配组件: complexResults.map(c => ({
                    名称: c.metadata.name,
                    优先级: c.metadata.priority,
                    标签数: c.metadata.tags ? c.metadata.tags.length : 0
                }))
            })

            logMessage(`🎯 复杂查询完成: 找到 ${complexResults.length} 个匹配组件`, 'info')
        }

        async function createDependencyChain() {
            logMessage('🔗 创建依赖链...', 'info')

            // 创建依赖链: A -> B -> C
            const componentA = {
                metadata: {
                    id: 'component-a',
                    name: '组件A（基础服务）',
                    type: 'data-source',
                    version: '1.0.0',
                    category: 'foundation',
                    tags: ['foundation', 'service'],
                    createdAt: Date.now(),
                    updatedAt: Date.now(),
                    enabled: true,
                    priority: 100
                },
                content: { level: 'foundation' }
            }

            const componentB = {
                metadata: {
                    id: 'component-b',
                    name: '组件B（中间层）',
                    type: 'renderer',
                    version: '1.0.0',
                    category: 'middleware',
                    tags: ['middleware', 'processor'],
                    dependencies: ['component-a'],
                    createdAt: Date.now(),
                    updatedAt: Date.now(),
                    enabled: true,
                    priority: 50
                },
                content: { level: 'middleware' }
            }

            const componentC = {
                metadata: {
                    id: 'component-c',
                    name: '组件C（应用层）',
                    type: 'card21-component',
                    version: '1.0.0',
                    category: 'application',
                    tags: ['application', 'ui'],
                    dependencies: ['component-b'],
                    createdAt: Date.now(),
                    updatedAt: Date.now(),
                    enabled: true,
                    priority: 10
                },
                content: { level: 'application' }
            }

            await registryEngine.register(componentA)
            await registryEngine.register(componentB)
            await registryEngine.register(componentC)

            updateStats()

            const cDependencies = registryEngine.getDependencies('component-c', true)
            const aDependents = registryEngine.getDependents('component-a', true)

            displayResult('依赖链创建结果', {
                依赖链: 'A <- B <- C',
                组件C的所有依赖: cDependencies,
                组件A的所有依赖者: aDependents
            })

            logMessage('✅ 依赖链创建完成', 'success')
        }

        function validateDependencies() {
            const allItems = registryEngine.getAll()
            const missingDependencies = []

            for (const item of allItems) {
                if (item.metadata.dependencies) {
                    const missing = item.metadata.dependencies.filter(depId => !registryEngine.has(depId))
                    if (missing.length > 0) {
                        missingDependencies.push({
                            component: item.metadata.id,
                            missing: missing
                        })
                    }
                }
            }

            const isValid = missingDependencies.length === 0

            displayResult('依赖验证结果', {
                验证状态: isValid ? '✅ 所有依赖完整' : '❌ 存在缺失依赖',
                缺失依赖: missingDependencies
            })

            if (isValid) {
                logMessage('✅ 依赖验证通过', 'success')
            } else {
                logMessage(`⚠️ 发现 ${missingDependencies.length} 个依赖问题`, 'warn')
            }
        }

        function analyzeDependencies() {
            const allItems = registryEngine.getAll()
            const dependencyAnalysis = {}

            for (const item of allItems) {
                const dependencies = registryEngine.getDependencies(item.metadata.id, false)
                const dependents = registryEngine.getDependents(item.metadata.id, false)

                dependencyAnalysis[item.metadata.id] = {
                    name: item.metadata.name,
                    directDependencies: dependencies.length,
                    directDependents: dependents.length,
                    dependencies: dependencies,
                    dependents: dependents
                }
            }

            displayResult('依赖关系分析', dependencyAnalysis)
            logMessage('📊 依赖关系分析完成', 'info')
        }

        async function testCircularDependency() {
            logMessage('🔄 测试循环依赖检测...', 'warn')

            try {
                // 尝试创建循环依赖 X -> Y -> X
                const componentX = {
                    metadata: {
                        id: 'component-x',
                        name: '组件X',
                        type: 'card21-component',
                        version: '1.0.0',
                        dependencies: ['component-y'],  // 依赖Y
                        createdAt: Date.now(),
                        updatedAt: Date.now(),
                        enabled: true,
                        priority: 10
                    },
                    content: { circular: true }
                }

                const componentY = {
                    metadata: {
                        id: 'component-y',
                        name: '组件Y',
                        type: 'card21-component',
                        version: '1.0.0',
                        dependencies: ['component-x'],  // 依赖X，形成循环
                        createdAt: Date.now(),
                        updatedAt: Date.now(),
                        enabled: true,
                        priority: 10
                    },
                    content: { circular: true }
                }

                // 先注册X（Y不存在，应该有警告但能成功）
                await registryEngine.register(componentX)

                // 再注册Y（会形成循环依赖）
                await registryEngine.register(componentY)

                updateStats()

                displayResult('循环依赖测试', {
                    结果: '循环依赖已创建（演示用途）',
                    组件X依赖: registryEngine.getDependencies('component-x'),
                    组件Y依赖: registryEngine.getDependencies('component-y'),
                    注意: '实际系统中应该检测并阻止循环依赖'
                })

                logMessage('⚠️ 循环依赖测试完成（仅演示）', 'warn')

            } catch (error) {
                logMessage(`❌ 循环依赖测试失败: ${error.message}`, 'error')
            }
        }

        async function registerCustomComponent() {
            const id = document.getElementById('customId').value.trim()
            const name = document.getElementById('customName').value.trim()
            const type = document.getElementById('customType').value
            const contentStr = document.getElementById('customContent').value.trim()

            if (!id || !name || !contentStr) {
                logMessage('❌ 请填写所有必需字段', 'error')
                return
            }

            try {
                const content = JSON.parse(contentStr)

                const component = {
                    metadata: {
                        id: id,
                        name: name,
                        type: type,
                        version: '1.0.0',
                        description: `自定义${name}组件`,
                        category: 'custom',
                        tags: ['custom', 'user-defined'],
                        createdAt: Date.now(),
                        updatedAt: Date.now(),
                        enabled: true,
                        priority: 20
                    },
                    content: content,
                    validate: () => {
                        logMessage('🔍 验证自定义组件...', 'info')
                        return true
                    },
                    initialize: async () => {
                        logMessage('🚀 初始化自定义组件...', 'info')
                    }
                }

                const success = await registryEngine.register(component)
                updateStats()

                if (success) {
                    displayResult('自定义组件注册', component.metadata)
                    logMessage(`✅ 自定义组件 ${name} 注册成功`, 'success')
                }

            } catch (error) {
                logMessage(`❌ JSON解析错误: ${error.message}`, 'error')
            }
        }

        function queryCustomComponent() {
            const id = document.getElementById('customId').value.trim()

            if (!id) {
                logMessage('❌ 请输入组件ID', 'error')
                return
            }

            const component = registryEngine.get(id)

            if (component) {
                displayResult('自定义组件查询', {
                    找到组件: true,
                    组件信息: component.metadata,
                    组件内容: component.content
                })
                logMessage(`✅ 找到组件: ${component.metadata.name}`, 'success')
            } else {
                displayResult('自定义组件查询', {
                    找到组件: false,
                    查询ID: id
                })
                logMessage(`⚠️ 未找到组件: ${id}`, 'warn')
            }
        }

        async function runPerformanceTest() {
            logMessage('⚡ 开始性能测试...', 'info')

            const testSizes = [10, 50, 100, 200]
            const results = []

            for (const size of testSizes) {
                // 注册性能测试
                const startTime = performance.now()
                const promises = []

                for (let i = 0; i < size; i++) {
                    const component = {
                        metadata: {
                            id: `perf-test-${size}-${i}`,
                            name: `性能测试组件 ${i}`,
                            type: 'card21-component',
                            version: '1.0.0',
                            category: 'performance',
                            tags: ['performance', 'test'],
                            createdAt: Date.now(),
                            updatedAt: Date.now(),
                            enabled: true,
                            priority: Math.random() * 100
                        },
                        content: { perfTest: true, index: i }
                    }
                    promises.push(registryEngine.register(component))
                }

                await Promise.all(promises)
                const registerTime = performance.now() - startTime

                // 查询性能测试
                const queryStart = performance.now()
                const queryResults = registryEngine.query({
                    category: 'performance',
                    tags: ['test']
                })
                const queryTime = performance.now() - queryStart

                results.push({
                    size: size,
                    registerTime: registerTime.toFixed(2),
                    queryTime: queryTime.toFixed(2),
                    avgRegisterTime: (registerTime / size).toFixed(3),
                    queryResults: queryResults.length
                })

                logMessage(`📊 测试 ${size} 个组件: 注册 ${registerTime.toFixed(2)}ms, 查询 ${queryTime.toFixed(2)}ms`, 'info')
            }

            updateStats()

            displayResult('性能测试结果', {
                测试规模: testSizes,
                详细结果: results,
                总体性能: registryEngine.getAveragePerformance().toFixed(2) + 'ms/操作'
            })

            logMessage('✅ 性能测试完成', 'success')
        }

        async function runErrorTest() {
            logMessage('🐛 开始错误处理测试...', 'warn')

            const errorTests = [
                {
                    name: '重复ID注册',
                    test: async () => {
                        const comp1 = {
                            metadata: {
                                id: 'duplicate-test',
                                name: '重复测试1',
                                type: 'card21-component',
                                version: '1.0.0',
                                createdAt: Date.now(),
                                updatedAt: Date.now(),
                                enabled: true,
                                priority: 10
                            },
                            content: {}
                        }

                        const comp2 = { ...comp1, metadata: { ...comp1.metadata, name: '重复测试2' } }

                        const result1 = await registryEngine.register(comp1)
                        const result2 = await registryEngine.register(comp2)

                        return { result1, result2 }
                    }
                },
                {
                    name: '无效元数据',
                    test: async () => {
                        const invalidComp = {
                            metadata: {
                                id: '',  // 空ID
                                name: '',  // 空名称
                                type: 'invalid-type',
                                version: '1.0.0',
                                createdAt: Date.now(),
                                updatedAt: Date.now(),
                                enabled: true,
                                priority: 10
                            },
                            content: {}
                        }

                        return await registryEngine.register(invalidComp)
                    }
                },
                {
                    name: '验证失败',
                    test: async () => {
                        const failingComp = {
                            metadata: {
                                id: 'validation-fail-test',
                                name: '验证失败测试',
                                type: 'card21-component',
                                version: '1.0.0',
                                createdAt: Date.now(),
                                updatedAt: Date.now(),
                                enabled: true,
                                priority: 10
                            },
                            content: {},
                            validate: () => {
                                throw new Error('验证过程中发生异常')
                            }
                        }

                        return await registryEngine.register(failingComp)
                    }
                }
            ]

            const errorResults = {}

            for (const errorTest of errorTests) {
                try {
                    const result = await errorTest.test()
                    errorResults[errorTest.name] = {
                        结果: result,
                        状态: '测试完成'
                    }
                } catch (error) {
                    errorResults[errorTest.name] = {
                        错误: error.message,
                        状态: '捕获异常'
                    }
                }
            }

            updateStats()

            displayResult('错误处理测试结果', errorResults)
            logMessage('✅ 错误处理测试完成', 'success')
        }

        async function clearAllData() {
            logMessage('🧹 清空所有数据...', 'warn')
            await registryEngine.clear()
            updateStats()

            // 清空结果显示
            document.getElementById('resultDisplay').innerHTML = ''

            displayResult('数据清理', {
                状态: '所有注册项已清空',
                清理时间: new Date().toLocaleString()
            })

            logMessage('✅ 数据清理完成', 'success')
        }

        // 事件监听器
        registryEngine.on('register', (metadata) => {
            updateStats()
        })

        registryEngine.on('unregister', (id) => {
            updateStats()
        })

        registryEngine.on('error', (errorInfo) => {
            console.error('Registry Engine Error:', errorInfo)
        })

        // 定期更新统计信息
        setInterval(updateStats, 2000)

        // 初始化
        window.addEventListener('load', () => {
            logMessage('🎉 Registry Engine 演示系统已就绪', 'success')
            updateStats()
        })
    </script>
</body>
</html>